package cn.com.idmy.cloud.mask;


import cn.com.idmy.base.FieldGetter;
import cn.com.idmy.base.util.LambdaUtil;
import org.dromara.hutool.core.lang.tuple.Pair;

import java.util.HashMap;
import java.util.Map;

public class Masks {
    private record FieldMaskConfig<T>(FieldGetter<T, String> field, MaskType maskType) {
    }

    private static final ThreadLocal<Map<String, Pair<Integer, Integer>>> threadLocal = new ThreadLocal<>();

    public static <T> void start(FieldGetter<T, String> field, MaskType maskType) {
        setMaskConfig(new FieldMaskConfig<>(field, maskType));
    }

    public static <T> void start(FieldGetter<T, String> field, MaskType maskType, FieldGetter<T, String> field2, MaskType maskType2) {
        setMaskConfig(new FieldMaskConfig<>(field, maskType), new FieldMaskConfig<>(field2, maskType2));
    }

    public static <T> void start(FieldGetter<T, String> field, MaskType maskType, FieldGetter<T, String> field2, MaskType maskType2, FieldGetter<T, String> field3, MaskType maskType3) {
        setMaskConfig(new FieldMaskConfig<>(field, maskType), new FieldMaskConfig<>(field2, maskType2), new FieldMaskConfig<>(field3, maskType3));
    }

    @SafeVarargs
    private static <T> void setMaskConfig(FieldMaskConfig<T>... configs) {
        var configMap = new HashMap<String, Pair<Integer, Integer>>();
        for (var config : configs) {
            var fieldName = LambdaUtil.getFieldName(config.field());
            var maskType = config.maskType();
            configMap.put(fieldName, new Pair<>(maskType.front(), maskType.back()));
        }
        threadLocal.set(configMap);
    }

    public static Map<String, Pair<Integer, Integer>> maskConfig() {
        return threadLocal.get();
    }

    /**
     * 不需要用户自己调用，会再全局处理
     */
    @Deprecated
    public static void clear() {
        threadLocal.remove();
    }
}